package flc.ast.activity;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;

import com.blankj.utilcode.util.ClipboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.endic.lib.model.Pronouncer;
import com.stark.speechrec.lib.ShortSpeechRecognizer;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.TranslateRecordAdapter;
import flc.ast.bean.MyTransRecordBean;
import flc.ast.databinding.ActivityTranslateBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import stark.common.apis.base.ShortSpeechRecRet;
import stark.common.base.IReqRetCallback;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.SolveEditTextScrollClash;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.other.LanCode;
import stark.common.other.ReqManager;
import stark.common.other.bean.TranslateRet;

public class TranslateActivity extends BaseAc<ActivityTranslateBinding> implements View.OnTouchListener {

    private LanCode mCurSelLanCodeFrom, mCurSelLanCodeTo;
    private boolean isRecord;
    private float downY;
    private int moveY = 0;
    private ShortSpeechRecognizer mSpeechRecognizer = ShortSpeechRecognizer.getInstance();
    private List<MyTransRecordBean> listShow = new ArrayList<>();
    private TranslateRecordAdapter recordAdapter;


    @Override
    protected int onCreate() {
        return R.layout.activity_translate;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(this, mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(this, mDataBinding.event5Container);
        mDataBinding.ivTranslateBack.setOnClickListener(v -> onBackPressed());
        mDataBinding.tvFrom.setOnClickListener(this);
        mDataBinding.tvTo.setOnClickListener(this);
        mDataBinding.tvStart.setOnClickListener(this);
        mDataBinding.ivRead.setOnClickListener(this);
        mDataBinding.ivResRead.setOnClickListener(this);
        mDataBinding.ivTakePicTrans.setOnClickListener(this);
        mDataBinding.ivSpeechTrans.setOnTouchListener(this);
        mDataBinding.etInput.setOnTouchListener(new SolveEditTextScrollClash(mDataBinding.etInput));
        mDataBinding.rvRecordList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mDataBinding.rvRecordList.setItemAnimator(new DefaultItemAnimator());
        recordAdapter = new TranslateRecordAdapter(this);
        mDataBinding.rvRecordList.setAdapter(recordAdapter);
        recordAdapter.setOnItemClickListener(new TranslateRecordAdapter.OnItemClickListener() {
            @Override
            public void onClick(MyTransRecordBean bean, int position) {

            }

            @Override
            public void onClickCopy(MyTransRecordBean bean, int position) {
                ClipboardUtils.copyText(bean.getTo());
                ToastUtils.showShort(R.string.have_copy);
            }

            @Override
            public void onClickDelete(MyTransRecordBean bean, int position) {
                listShow.remove(position);
                AppSpUtils.saveTransRecordList(listShow);
                getData();
            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvFrom://初始语言
                SelLanguageActivity.type = 0;
                SelLanguageActivity.mCurSelLanCodeFrom = mCurSelLanCodeFrom;
                SelLanguageActivity.mCurSelLanCodeTo = mCurSelLanCodeTo;
                Intent intent = new Intent(this, SelLanguageActivity.class);
                startActivityForResult(intent, Content.SEL_LAN);
                break;
            case R.id.tvTo://目标语言
                SelLanguageActivity.type = 1;
                SelLanguageActivity.mCurSelLanCodeFrom = mCurSelLanCodeFrom;
                SelLanguageActivity.mCurSelLanCodeTo = mCurSelLanCodeTo;
                Intent intent1 = new Intent(this, SelLanguageActivity.class);
                startActivityForResult(intent1, Content.SEL_LAN);
                break;
            case R.id.tvStart://开始翻译
                startTranslate();
                break;
            case R.id.ivRead://播放
                if (mCurSelLanCodeFrom != LanCode.EN) {
                    ToastUtils.showShort(R.string.not_support_chinese_playback);
                    return;
                }
                String speakText = mDataBinding.etInput.getText().toString();
                if (TextUtils.isEmpty(speakText)) return;
                Pronouncer.getInstance().playByEn(speakText);
                break;
            case R.id.ivResRead:
                if (mCurSelLanCodeTo != LanCode.EN) {
                    ToastUtils.showShort(R.string.not_support_chinese_playback);
                    return;
                }
                String speakText1 = mDataBinding.tvRes.getText().toString();
                if (TextUtils.isEmpty(speakText1)) return;
                Pronouncer.getInstance().playByEn(speakText1);
                break;
            case R.id.ivTakePicTrans://拍照翻译
                startActivity(TakePicTransActivity.class);
                break;
        }
    }

    @Override
    protected void initData() {
        mCurSelLanCodeFrom = LanCode.ZH;
        mCurSelLanCodeTo = LanCode.EN;
        mDataBinding.tvFrom.setText(mCurSelLanCodeFrom.getName());
        mDataBinding.tvTo.setText(mCurSelLanCodeTo.getName());
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.RECORD_AUDIO)
                .reqPermissionDesc(getString(R.string.get_record_audio))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        String recFilePath = FileUtil.generateFilePathByName("stt", "stt.pcm");
                        mSpeechRecognizer.startRecAudio(recFilePath);
                        isRecord = true;
                    }
                })
                .request();
    }

    private void getData() {
        if (listShow != null) {
            listShow.clear();
        }
        listShow = AppSpUtils.getTransRecordList();
        if (listShow != null && listShow.size() != 0) {
            recordAdapter.setmDatas(listShow);
            recordAdapter.notifyDataSetChanged();
            mDataBinding.rvRecordList.setAdapter(recordAdapter);
            mDataBinding.rvRecordList.refreshDrawableState();
            mDataBinding.rvRecordList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvRecordList.setVisibility(View.GONE);
        }
    }

    private void startTranslate() {
        showDialog(getString(R.string.translation_loading));
        ReqManager.getInstance().translate(this, mDataBinding.etInput.getText().toString(),
                mCurSelLanCodeFrom, mCurSelLanCodeTo, new IReqRetCallback<TranslateRet>() {
                    @Override
                    public void onResult(boolean success, String msg, @Nullable TranslateRet result) {
                        if (result != null) {
                            mDataBinding.ivRead.setVisibility(View.VISIBLE);
                            mDataBinding.ivResRead.setVisibility(View.VISIBLE);
                            mDataBinding.llRes.setVisibility(View.VISIBLE);
                            mDataBinding.tvRes.setText(result.getResult());
//                            mHomeAdapter.addData(new TranslateBean(mDataBinding.etInput.getText().toString(),
//                                    result.getResult()));
                            List<MyTransRecordBean> listSp = AppSpUtils.getTransRecordList();
                            List<MyTransRecordBean> listSave = new ArrayList<>();
                            listSave.add(new MyTransRecordBean(mDataBinding.etInput.getText().toString(), result.getResult()));
                            if (listSp != null && listSp.size() != 0) {
                                listSp.addAll(listSave);
                                AppSpUtils.saveTransRecordList(listSp);
                            } else {
                                AppSpUtils.saveTransRecordList(listSave);
                            }
                            getData();
                        } else {
                            ToastUtils.showShort(msg);
                        }
                        dismissDialog();
                    }
                });
    }

    private void startRecognize() {
        showDialog(getString(R.string.identifying));
        mSpeechRecognizer.startRecognize(this, mSpeechRecognizer.getRecFilePath(), new IReqRetCallback<ShortSpeechRecRet>() {
            @Override
            public void onResult(boolean success, String msg, @Nullable ShortSpeechRecRet result) {
                dismissDialog();
                if (result == null || result.result == null) {
                    ToastUtils.showShort(getString(R.string.rec_audio_def));
                    return;
                }
                StringBuilder builder = new StringBuilder();
                for (String str : result.result) {
                    builder.append(str);
                }
                mDataBinding.etInput.setText(builder.toString());
                startTranslate();
            }
        });
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        moveY = (int) (event.getY() - downY);
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                //通知父控件不要干扰
                v.getParent().requestDisallowInterceptTouchEvent(true);
                downY = event.getY();
                mDataBinding.ivImage.setVisibility(View.VISIBLE);
                mDataBinding.ivImage.setImageResource(R.drawable.skfy1);
                getPermission();
                break;
            case MotionEvent.ACTION_UP:
                v.getParent().requestDisallowInterceptTouchEvent(false);
                mDataBinding.ivImage.setVisibility(View.GONE);
                if (isRecord) {
                    mSpeechRecognizer.stopRecAudio();
                    startRecognize();
                } else {
                    mSpeechRecognizer.stopRecAudio();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                //通知父控件不要干扰
                v.getParent().requestDisallowInterceptTouchEvent(true);
                if (moveY < 0 && moveY < -20) {
                    mDataBinding.ivImage.setImageResource(R.drawable.shqx1);
                    isRecord = false;
                    mSpeechRecognizer.stopRecAudio();
                }
                break;
        }
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Content.SEL_LAN) {
                LanCode selLanCode = (LanCode) data.getSerializableExtra(Content.LAN_CODE);
                if (SelLanguageActivity.type == 0) {
                    mCurSelLanCodeFrom = selLanCode;
                    mDataBinding.tvFrom.setText(mCurSelLanCodeFrom.getName());
                } else {
                    mCurSelLanCodeTo = selLanCode;
                    mDataBinding.tvTo.setText(mCurSelLanCodeTo.getName());
                }
            }
        }
    }
}